import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository ,In} from 'typeorm';
import { menus } from './menu.entity'; // 修改实体类命名

class MenuInfo {
    isShow: string;
    parentId: number; // 修改属性名为小驼峰命名法
    name: string;
    path: number;
}

@Injectable()
export class MenuService {
    constructor(
        @InjectRepository(menus) private readonly menuRepository: Repository<menus>, // 修改实体类引用
    ) { }

    // 查询菜单列表通过id数组
    async findListByIds(ids: number[]): Promise<menus[]> {
        try {
            return await this.menuRepository.findBy({ id: In(ids) }); // 使用 in 查询条件
        } catch (error) {
            throw new Error('Failed to fetch menus by IDs');
        }
    }

    // 查询菜单列表
    async findList(permissions: number | null): Promise<menus[]> {
        try {
            if (permissions !== undefined && permissions !== null) {
                return await this.menuRepository.findBy({ permissions });
            }
            return await this.menuRepository.find();
        } catch (error) {
            throw new Error('Failed to fetch menus');
        }
    }

    // 删除菜单列表
    async delete(id: number): Promise<object> {
        try {
            const result = await this.menuRepository.delete(id);
            return { success: true, ...result };
        } catch (error) {
            throw new Error('Failed to delete menu');
        }
    }

    // 新增菜单列表
    async addMenu(info: menus): Promise<object> {
        try {
            const newMenu = this.menuRepository.create(info);
            const result = await this.menuRepository.save(newMenu);
            return { success: true, data: result };
        } catch (error) {
            throw new Error('Failed to add menu');
        }
    }

    // 修改菜单列表
    async editMenu(info: menus): Promise<object> {
        try {
            const result = await this.menuRepository.update(info.id, info);
            return { success: true, ...result };
        } catch (error) {
            throw new Error('Failed to edit menu');
        }
    }

    // 菜单列表详情
    async oneMenu(id: number): Promise<menus | null> {
        try {
            return await this.menuRepository.findOneBy({ id });
        } catch (error) {
            throw new Error('Failed to fetch menu details');
        }
    }
}